package com.itheima.mall.filter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.itheima.mall.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class GlobleFilter implements GlobalFilter {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
   //1.获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //放过不能过滤的接口
        String url = request.getURI().getPath();
        if (StrUtil.equals(url, "/admin/login") || StrUtil.equals(url, "/admin/info")) {
            return chain.filter(exchange);
        }
        //2.获取header中的Authorization的值
        String token = request.getHeaders().getFirst("token");
        //3.远程调用sso解析token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i==1 || i==2) {
            return exchange.getResponse().setComplete();
        }
        String uid= Convert.toStr(claimsBody.get("id"));
        if (uid != null) {
            String redisKey = "AUTH_USER_ID";
            //将id存入redis
            stringRedisTemplate.opsForValue().set(redisKey, Convert.toStr(uid));
            //放行
            return chain.filter(exchange);
        }
        //未登录认证
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
